<template>
  <div
    class="relative h-1/3"
    ref="videoContainer"
    :class="{ 'video-fullscreen': playerStore.isFullScreen }"
  >
    <video
      ref="videoElement"
      id="videoElement"
      class="h-full w-full"
      playsinline
      preload="metadata"
      webkit-playsinline
    >
      <source
        :src="videoUrl"
        v-if="!videoUrl.startsWith('webrtc://')"
        :type="
          videoUrl.endsWith('.m3u8') ? 'application/x-mpegURL' : 'video/mp4'
        "
      />
    </video>
    <!-- 加载提示 -->
    <div
      v-if="isLoading"
      class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70 text-white text-sm"
    >
      直播加载中...
    </div>
    <div
      v-if="error"
      class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70 text-white text-sm"
    >
      {{ error }}
    </div>
    <AutoPlay @close="play" type="直播" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import { usePlayerStore } from "@/store/usePlayer";
import AutoPlay from "@/components/AutoPlay.vue";
import { PlayerFactory } from "@/utils/playerFactory";
import "tcplayer.js/dist/tcplayer.min.css";

const playerStore = usePlayerStore();
const props = defineProps<{
  videoUrl: string;
  videoPoster: string;
  showTime: boolean;
}>();

const emit = defineEmits<{
  (e: "update", currentTime: number): void;
}>();

const videoElement = ref<HTMLVideoElement | null>(null);
const videoContainer = ref<HTMLElement | null>(null);
const isLoading = ref(false);
const error = ref("");
const player = ref<any>(null);

let lastTime = 0;
let watchedTime = 0;

const showLoading = () => {
  isLoading.value = true;
};

const hideLoading = () => {
  isLoading.value = false;
};

const disableDblclick = () => {
  videoContainer.value?.addEventListener(
    "dblclick",
    e => {
      e.preventDefault();
      e.stopImmediatePropagation();
      player.value?.player.fullscreen?.toggle();
    },
    true
  );
};

onMounted(() => {
  if (videoElement.value) {
    try {
      player.value = PlayerFactory.createPlayer({
        videoElement: videoElement.value,
        videoUrl: props.videoUrl,
        videoPoster: props.videoPoster,
        showTime: props.showTime,
        isPortrait: false,
        onTimeUpdate: time => {
          if (!isNaN(lastTime)) {
            let delta = time - lastTime;
            if (delta > 0 && delta < 1.0) {
              watchedTime += delta;
            }
          }
          lastTime = time;
          emit("update", watchedTime);
        },
        onLoadingChange: loading => {
          isLoading.value = loading;
        }
      });

      // 监听全屏事件
      player.value.onFullscreenChange?.(isFullscreen => {
        if (videoContainer.value) {
          playerStore.setFullScreen(isFullscreen);
        }
      });

      disableDblclick();
    } catch (e) {
      error.value = "播放器初始化失败，请刷新重试";
      console.error("Player initialization failed:", e);
    }
  }
});

watch(
  () => playerStore.isFullScreen,
  (nv, ov) => {
    if (!nv) {
      player.value?.fullscreen?.exit();
    }
  }
);

const play = () => {
  player.value?.play();
};

onUnmounted(() => {
  player.value?.destroy();
});
</script>

<style scoped lang="less">
:deep(.plyr__controls__item.plyr__control.plyr__control--pressed:first-child) {
  display: none;
}
:deep(.plyr__controls__item.plyr__control:last-child) {
  margin-right: 5vw;
}
:deep(.plyr) {
  height: 100%;
}

.video-fullscreen {
  transform: rotate(90deg) !important;
  transform-origin: 0 100% !important;
  width: 100vh !important;
  height: 100vw !important;
  position: fixed !important;
  top: -100vw !important;
  left: 0 !important;
  z-index: 9999 !important;
  #videoElement {
    width: 100% !important;
    height: 100% !important;
  }
}
</style>
